<template>
  <div class="container">
    <div class="top">
      <div>
        <span>
          <span>区段：&nbsp;&nbsp;</span>
          <el-tree-select v-model="searchData.sectionId" :data="dataSource"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange">
          </el-tree-select>
        </span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <span>
          <span>工区：&nbsp;&nbsp;</span>
          <el-tree-select v-model="searchData.workAreaId" :data="dataSourceArea"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly>
          </el-tree-select>
        </span>&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="primary" plain @click="search">查询</el-button>
        <el-button type="primary" plain @click="resetSearch">重置</el-button>
      </div>
      <el-button type="primary" plain @click="add">新增</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="序号" width="55"> </el-table-column>
      <el-table-column prop="section" label="区段"> </el-table-column>
      <el-table-column prop="workArea" label="工区"> </el-table-column>
      <el-table-column prop="project" label="演练项目"> </el-table-column>
      <el-table-column prop="drillTime" label="演练时间"> </el-table-column>
      <el-table-column prop="date" label="演练方案">
        <template #default="scope">
          <el-button text plain @click="details(scope.row,'fa')">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="演练总结">
        <template #default="scope">
          <el-button text plain @click="details(scope.row,'zj')">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作">
        <template #default="scope">
          <el-icon title="编辑" @click="edit(scope.row)">
            <Edit />
          </el-icon>
          &nbsp;
          <el-icon title="删除" @click="del(scope.row)">
            <Delete />
          </el-icon>
        </template> </el-table-column>
    </el-table>

    <!-- 新增对话框 -->
    <el-dialog title="应急演练" v-model="open" width="500px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区段" prop="sectionId">
          <el-tree-select v-model="form.sectionId" :data="dataSource"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="工区" prop="workAreaId">
          <el-tree-select v-model="form.workAreaId" :data="dataSourceArea"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly>
          </el-tree-select>
        </el-form-item>
        <el-form-item label="时间" prop="drillTime">
          <el-date-picker v-model="form.drillTime" type="date" placeholder="请选择时间" style="width: 100%;"
            value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="演练项目" prop="project">
          <el-input v-model="form.project" placeholder="请输入演练项目" />
        </el-form-item>
        <el-form-item label="演练方案" prop="project">
          <el-upload ref="uploadRef" v-model:file-list="fileListPlan" accept=".pdf" :limit="1"
            :http-request="httpRequestPlan">
            <template #trigger>
              <el-button type="primary">上传</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传pdf格式文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="演练总结" prop="project">
          <el-upload ref="uploadRef" v-model:file-list="fileList" accept=".pdf" :limit="1" :http-request="httpRequest">
            <template #trigger>
              <el-button type="primary">上传</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传pdf格式文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog :title="title" v-model="openFile" width="80vw" append-to-body>
      <embed name="showName" :src="showUrl" style="overflow: auto; width: 100%; height: 70vh;" hidden="true">
      <div style="display: flex;justify-content: center;">
        <!-- <el-button type="primary" @click="delFile" style="margin: 0 auto;">删除</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    getDrill,
    delDrill,
    addDrill,
    editDrill,
    getDeptBy,
    getTreeList,
    uploadFile
  } from "@/api/work";
  const {
    proxy
  } = getCurrentInstance();

  //总结 上传
  const fileList = ref([])

  function httpRequest(date) {
    let file = date.file
    if (/\.pdf/.test(file.name)) {
      const formData = new FormData()
      formData.append('file', file)
      uploadFile(formData).then(res => {
        if (res.code = 200) {
          ElMessage({
            type: 'success',
            message: '上传成功',
          })
          form.value.summaryFileName = res.data.name
          form.value.summaryFileUrl = res.data.url
        }
      })
    } else {
      fileList.value = []
      return ElMessage({
        type: 'error',
        message: '只能上传pdf格式的文件',
      })
    }
  }
  //方案 上传
  const fileListPlan = ref([])

  function httpRequestPlan(date) {
    let file = date.file
    if (/\.pdf/.test(file.name)) {
      const formData = new FormData()
      formData.append('file', file)
      uploadFile(formData).then(res => {
        if (res.code = 200) {
          ElMessage({
            type: 'success',
            message: '上传成功',
          })
          form.value.planFileName = res.data.name
          form.value.planFileUrl = res.data.url
        }
      })
    } else {
      fileListPlan.value = []
      return ElMessage({
        type: 'error',
        message: '只能上传pdf格式的文件',
      })
    }
  }

  const open = ref(false)
  const tableData = ref([])
  const loading = ref(true);

  function getList() {
    loading.value = true;
    getDrill().then(res => {
      tableData.value = res.rows
      loading.value = false
    })
  }
  getList()
  //区段数据
  const dataSource = ref([])
  const dataSourceArea = ref([])

  function getTree() {
    getTreeList().then(res => {
      dataSource.value = res.data
    })
  }
  getTree()

  function treeChange(id) {
    searchData.value.workAreaId = ''
    form.value.workAreaId = ''
    getDeptBy({
      parentId: id
    }).then(res => {
      dataSourceArea.value = res.data
    })
  }

  const searchData = ref({
    sectionId: '',
    workAreaId: ''
  })

  function search() {
    getDrill(searchData.value).then(res => {
      tableData.value = res.rows
    })
  }

  function resetSearch() {
    searchData.value = {
      sectionId: '',
      workAreaId: ''
    }
    getList()
  }

  function add() {
    fileList.value = []
    fileListPlan.value = []
    open.value = true
    form.value = {}
  }

  function del(data) {
    ElMessageBox.confirm(
        '确认删除吗？',
        'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        delDrill(data.id).then(res => {
          ElMessage({
            type: 'success',
            message: '已删除',
          })
          getList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }

  function edit(row) {
    fileList.value = []
    fileListPlan.value = []
    form.value = row
    if (form.value.summaryFileName && form.value.summaryFileUrl) {
      fileList.value = [{
        name: form.value.summaryFileName,
        url: form.value.summaryFileUrl
      }]
    }
    if (form.value.planFileName && form.value.planFileUrl) {
      fileListPlan.value = [{
        name: form.value.planFileName,
        url: form.value.planFileUrl
      }]
    }

    getDeptBy({
      parentId: row.sectionId
    }).then(res => {
      dataSourceArea.value = res.data
    })
    open.value = true
  }

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      postCode: undefined,
      postName: undefined,
      phone: undefined
    },
    rules: {
      // phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
      // postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
      // postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
      // postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
    }
  });
  const {
    queryParams,
    form,
    rules
  } = toRefs(data);

  function cancel() {
    open.value = false
  }

  function submitForm() {
    if (fileList.value.length == 0) {
      form.value.summaryFileName = ''
      form.value.summaryFileUrl = ''
    }
    if (fileListPlan.value.length == 0) {
      form.value.planFileName = ''
      form.value.planFileUrl = ''
    }
    proxy.$refs["postRef"].validate(valid => {
      if (valid) {
        if (form.value.id != undefined) {
          editDrill(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList()
          });
        } else {
          addDrill(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList()
          });
        }
      }
    });
  }

  const openFile = ref(false)
  const title = ref('')

  const showUrl = ref('')
  const showName = ref('')

  function details(row, flag) {
    if (flag == 'fa') {
      title.value = '演练方案'
      showUrl.value = row.planFileUrl
      showName.value = row.planFileName
    } else {
      title.value = '演练总结'
      showUrl.value = row.summaryFileUrl
      showName.value = row.summaryFileName
    }
    openFile.value = true
  }

  function delFile() {
    openFile.value = false
  }
</script>

<style lang='scss' scoped>
  .container {
    height: 100%;
    width: 100%;
    padding: 20px;
  }

  .top {
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: space-between;
  }

  .end {
    justify-content: flex-end;
  }

  :deep(.el-table .el-table__cell) {
    text-align: center;
  }
</style>